package middleware

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"server/internal/app/model"
	"server/internal/app/service"
	"server/internal/core/server"
)

var rbacService = service.NewAdminRbacService()

func Permission() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		adminID := GetCurrentAdminID(ctx)
		if adminID == 0 {
			server.DefaultController.Error(ctx, server.UnauthorizedError)
			ctx.Abort()
			return
		}

		permissionType := model.PermissionTypeApi
		permissionPath := fmt.Sprintf("%s:%s:%s", permissionType, ctx.Request.Method, ctx.FullPath())
		hasPermission := rbacService.CheckPermission(ctx, adminID, permissionType, permissionPath)
		if !hasPermission {
			server.DefaultController.Error(ctx, server.ForbiddenError)
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}
